# -*- coding:utf-8 -*
from __future__ import print_function
from flask import Flask, jsonify, render_template,request
import urllib2
import json
import time
import urllib
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
app = Flask(__name__)


@app.route('/getinfo')
def hello_world():
    response = urllib2.urlopen("https://pub.alimama.com/items/search.json?q=%E7%A5%9E%E5%A5%87&toPage=1&perPageSize=40&startTkRate=5&startTotalnum=20&endTotalnum=99999&startPrice=8&endPrice=9999&sort=_totalfee&_t=1490230738&_input_charset=utf-8")
    hjson = json.loads(response.read())
    return jsonify(hjson['data']['pageList'])


@app.route('/index')
def index():
    return render_template('index.html')

@app.route('/')
def start():
    return render_template('index.html')


@app.route('/geturl', methods=['get', 'post'])
def geturl():
    if request.method == 'POST':
        data = {}
        for item in request.form:
            data[item] = request.form[item]
        url = parseurl(data)
        data['page_index'] = "2";
        url2 = parseurl(data);
        data['page_index'] = "3";
        url3 = parseurl(data);
        response = urllib2.urlopen(url)
        response2 = urllib2.urlopen(url2)
        response3 = urllib2.urlopen(url3)
        hjson = json.loads(response.read())
        hjson2 = json.loads(response2.read())
        hjson3 = json.loads(response3.read())
        for item in hjson['data']['pageList']:
            print(item['auctionUrl'])
        data = json.dumps(hjson['data']['pageList']+hjson2['data']['pageList']+hjson3['data']['pageList'], ensure_ascii=False)
        return render_template("list.html", data=data)


def parseurl(data):
    data['timestrmp'] = int(time.time())
    if data.has_key('page_index') is not True:
        data['page_index'] = "1"
    ori_url = "https://pub.alimama.com/items/search.json?q=" + data['keyword'] + \
              "&toPage=" + data['page_index'] + "&perPageSize=40&startTkRate=" + data['earning'] + "&startTotalnum=" + \
              data["low_recommend"] + \
              "&endTotalnum=" + data['high_recommend'] + "&startPrice=" + data['low_price'] + "&endPrice=" + data['high_price'] + \
              "&sort=_totalfee&_t=1490230738&_input_charset=utf-8"
    return urllib.unquote(ori_url)

if __name__ == '__main__':
    app.run(debug='true')
